package com.ruoyi.blindBoxManage.service.impl;

import com.ruoyi.blindBoxManage.domain.BlindBox;
import com.ruoyi.blindBoxManage.mapper.BlindBoxMapper;
import com.ruoyi.blindBoxManage.mapper.BlindBoxProductMapper;
import com.ruoyi.blindBoxManage.mapper.BoxMapper;
import com.ruoyi.blindBoxManage.service.IBlindBoxService;
import com.ruoyi.common.utils.DateUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 盲盒配置Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-12
 */
@Service
public class BlindBoxServiceImpl implements IBlindBoxService {
    @Autowired
    private BlindBoxMapper blindBoxMapper;
    @Resource
    private BoxMapper boxMapper;
    @Resource
    private BlindBoxProductMapper blindBoxProductMapper;

    /**
     * 查询盲盒配置
     *
     * @param id 盲盒配置主键
     * @return 盲盒配置
     */
    @Override
    public BlindBox selectBlindBoxById(Long id) {
        return blindBoxMapper.selectBlindBoxById(id);
    }

    /**
     * 查询盲盒配置列表
     *
     * @param blindBox 盲盒配置
     * @return 盲盒配置
     */
    @Override
    public List<BlindBox> selectBlindBoxList(BlindBox blindBox) {
        return blindBoxMapper.selectBlindBoxList(blindBox);
    }

    /**
     * 新增盲盒配置
     *
     * @param blindBox 盲盒配置
     * @return 结果
     */
    @Override
    public int insertBlindBox(BlindBox blindBox) {
        blindBox.setCreateTime(DateUtils.getNowDate());
        return blindBoxMapper.insertBlindBox(blindBox);
    }

    /**
     * 修改盲盒配置
     *
     * @param blindBox 盲盒配置
     * @return 结果
     */
    @Override
    public int updateBlindBox(BlindBox blindBox) {
        blindBox.setUpdateTime(DateUtils.getNowDate());
        return blindBoxMapper.updateBlindBox(blindBox);
    }

    /**
     * 批量删除盲盒配置
     *
     * @param ids 需要删除的盲盒配置主键
     * @return 结果
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int deleteBlindBoxByIds(Long[] ids) {
        for (Long id : ids) {
            //查询箱子是否有绑定的盲盒
            Integer blindBoxCount = boxMapper.selectCountByBlindBoxId(id);
            if (blindBoxCount > 0) {
                throw new RuntimeException("id为:" + id + " 有箱子绑定");
            }
            //查询商品是否有绑定的盲盒
            Integer count = blindBoxProductMapper.selectCountByBlindBoxId(id);
            if (count > 0) {
                throw new RuntimeException("id为:" + id + " 有商品绑定");
            }
        }
        return blindBoxMapper.deleteBlindBoxByIds(ids);
    }

    /**
     * 删除盲盒配置信息
     *
     * @param id 盲盒配置主键
     * @return 结果
     */
    @Override
    public int deleteBlindBoxById(Long id) {
        return blindBoxMapper.deleteBlindBoxById(id);
    }

}
